import { create } from 'zustand';
import { 
  Tenant, 
  Organization, 
  User, 
  Role, 
  Permission, 
  Department, 
  Position,
  SubscriptionPlan,
  TenantSubscription,
  OrganizationSubscription
} from '@/types';

// 数据状态接口
interface DataState {
  // 缓存数据
  tenants: Tenant[];
  organizations: Organization[];
  users: User[];
  roles: Role[];
  permissions: Permission[];
  departments: Department[];
  positions: Position[];
  subscriptionPlans: SubscriptionPlan[];
  tenantSubscriptions: TenantSubscription[];
  organizationSubscriptions: OrganizationSubscription[];
  
  // 加载状态
  loading: {
    tenants: boolean;
    organizations: boolean;
    users: boolean;
    roles: boolean;
    permissions: boolean;
    departments: boolean;
    positions: boolean;
    subscriptionPlans: boolean;
    tenantSubscriptions: boolean;
    organizationSubscriptions: boolean;
  };
  
  // 错误状态
  errors: {
    tenants: string | null;
    organizations: string | null;
    users: string | null;
    roles: string | null;
    permissions: string | null;
    departments: string | null;
    positions: string | null;
    subscriptionPlans: string | null;
    tenantSubscriptions: string | null;
    organizationSubscriptions: string | null;
  };
  
  // 最后更新时间
  lastUpdated: {
    tenants: string | null;
    organizations: string | null;
    users: string | null;
    roles: string | null;
    permissions: string | null;
    departments: string | null;
    positions: string | null;
    subscriptionPlans: string | null;
    tenantSubscriptions: string | null;
    organizationSubscriptions: string | null;
  };
  
  // 动作
  // 租户相关
  setTenants: (tenants: Tenant[]) => void;
  addTenant: (tenant: Tenant) => void;
  updateTenant: (id: string, tenant: Partial<Tenant>) => void;
  removeTenant: (id: string) => void;
  refreshTenants: () => Promise<void>;
  
  // 组织相关
  setOrganizations: (organizations: Organization[]) => void;
  addOrganization: (organization: Organization) => void;
  updateOrganization: (id: string, organization: Partial<Organization>) => void;
  removeOrganization: (id: string) => void;
  refreshOrganizations: (tenantId?: string) => Promise<void>;
  
  // 用户相关
  setUsers: (users: User[]) => void;
  addUser: (user: User) => void;
  updateUser: (id: string, user: Partial<User>) => void;
  removeUser: (id: string) => void;
  refreshUsers: (filters?: any) => Promise<void>;
  
  // 角色相关
  setRoles: (roles: Role[]) => void;
  addRole: (role: Role) => void;
  updateRole: (id: string, role: Partial<Role>) => void;
  removeRole: (id: string) => void;
  refreshRoles: (tenantId?: string) => Promise<void>;
  
  // 权限相关
  setPermissions: (permissions: Permission[]) => void;
  refreshPermissions: () => Promise<void>;
  
  // 部门相关
  setDepartments: (departments: Department[]) => void;
  addDepartment: (department: Department) => void;
  updateDepartment: (id: string, department: Partial<Department>) => void;
  removeDepartment: (id: string) => void;
  refreshDepartments: (organizationId?: string) => Promise<void>;
  
  // 岗位相关
  setPositions: (positions: Position[]) => void;
  addPosition: (position: Position) => void;
  updatePosition: (id: string, position: Partial<Position>) => void;
  removePosition: (id: string) => void;
  refreshPositions: (departmentId?: string) => Promise<void>;
  
  // 订阅相关
  setSubscriptionPlans: (plans: SubscriptionPlan[]) => void;
  setTenantSubscriptions: (subscriptions: TenantSubscription[]) => void;
  setOrganizationSubscriptions: (subscriptions: OrganizationSubscription[]) => void;
  refreshSubscriptionPlans: () => Promise<void>;
  refreshTenantSubscriptions: (tenantId?: string) => Promise<void>;
  refreshOrganizationSubscriptions: (organizationId?: string) => Promise<void>;
  
  // 通用动作
  setLoading: (key: keyof DataState['loading'], loading: boolean) => void;
  setError: (key: keyof DataState['errors'], error: string | null) => void;
  clearCache: () => void;
  clearErrors: () => void;
  
  // 查询辅助
  getTenantById: (id: string) => Tenant | undefined;
  getOrganizationById: (id: string) => Organization | undefined;
  getUserById: (id: string) => User | undefined;
  getRoleById: (id: string) => Role | undefined;
  getPermissionById: (id: string) => Permission | undefined;
  getDepartmentById: (id: string) => Department | undefined;
  getPositionById: (id: string) => Position | undefined;
  
  // 关系查询
  getOrganizationsByTenant: (tenantId: string) => Organization[];
  getUsersByOrganization: (organizationId: string) => User[];
  getDepartmentsByOrganization: (organizationId: string) => Department[];
  getPositionsByDepartment: (departmentId: string) => Position[];
  getRolesByTenant: (tenantId: string) => Role[];
}

// 生成默认状态
const createDefaultState = () => ({
  tenants: [],
  organizations: [],
  users: [],
  roles: [],
  permissions: [],
  departments: [],
  positions: [],
  subscriptionPlans: [],
  tenantSubscriptions: [],
  organizationSubscriptions: [],
  
  loading: {
    tenants: false,
    organizations: false,
    users: false,
    roles: false,
    permissions: false,
    departments: false,
    positions: false,
    subscriptionPlans: false,
    tenantSubscriptions: false,
    organizationSubscriptions: false,
  },
  
  errors: {
    tenants: null,
    organizations: null,
    users: null,
    roles: null,
    permissions: null,
    departments: null,
    positions: null,
    subscriptionPlans: null,
    tenantSubscriptions: null,
    organizationSubscriptions: null,
  },
  
  lastUpdated: {
    tenants: null,
    organizations: null,
    users: null,
    roles: null,
    permissions: null,
    departments: null,
    positions: null,
    subscriptionPlans: null,
    tenantSubscriptions: null,
    organizationSubscriptions: null,
  },
});

// 获取授权头
const getAuthHeaders = () => ({
  'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
  'Content-Type': 'application/json',
});

// 数据状态存储
export const useDataStore = create<DataState>((set, get) => ({
  ...createDefaultState(),
  
  // 租户相关
  setTenants: (tenants: Tenant[]) => {
    set((state) => ({
      tenants,
      lastUpdated: { ...state.lastUpdated, tenants: new Date().toISOString() },
    }));
  },
  
  addTenant: (tenant: Tenant) => {
    set((state) => ({ tenants: [...state.tenants, tenant] }));
  },
  
  updateTenant: (id: string, tenant: Partial<Tenant>) => {
    set((state) => ({
      tenants: state.tenants.map((t) => 
        t.id === id ? { ...t, ...tenant } : t
      ),
    }));
  },
  
  removeTenant: (id: string) => {
    set((state) => ({
      tenants: state.tenants.filter((t) => t.id !== id),
    }));
  },
  
  refreshTenants: async () => {
    const { setLoading, setError } = get();
    setLoading('tenants', true);
    setError('tenants', null);
    
    try {
      const response = await fetch('/api/tenants', {
        headers: getAuthHeaders(),
      });
      
      if (!response.ok) {
        throw new Error('获取租户列表失败');
      }
      
      const tenants = await response.json();
      get().setTenants(tenants);
    } catch (error) {
      setError('tenants', error instanceof Error ? error.message : '未知错误');
    } finally {
      setLoading('tenants', false);
    }
  },
  
  // 组织相关
  setOrganizations: (organizations: Organization[]) => {
    set((state) => ({
      organizations,
      lastUpdated: { ...state.lastUpdated, organizations: new Date().toISOString() },
    }));
  },
  
  addOrganization: (organization: Organization) => {
    set((state) => ({ organizations: [...state.organizations, organization] }));
  },
  
  updateOrganization: (id: string, organization: Partial<Organization>) => {
    set((state) => ({
      organizations: state.organizations.map((o) => 
        o.id === id ? { ...o, ...organization } : o
      ),
    }));
  },
  
  removeOrganization: (id: string) => {
    set((state) => ({
      organizations: state.organizations.filter((o) => o.id !== id),
    }));
  },
  
  refreshOrganizations: async (tenantId?: string) => {
    const { setLoading, setError } = get();
    setLoading('organizations', true);
    setError('organizations', null);
    
    try {
      const url = tenantId ? `/api/organizations?tenantId=${tenantId}` : '/api/organizations';
      const response = await fetch(url, {
        headers: getAuthHeaders(),
      });
      
      if (!response.ok) {
        throw new Error('获取组织列表失败');
      }
      
      const organizations = await response.json();
      get().setOrganizations(organizations);
    } catch (error) {
      setError('organizations', error instanceof Error ? error.message : '未知错误');
    } finally {
      setLoading('organizations', false);
    }
  },
  
  // 用户相关
  setUsers: (users: User[]) => {
    set((state) => ({
      users,
      lastUpdated: { ...state.lastUpdated, users: new Date().toISOString() },
    }));
  },
  
  addUser: (user: User) => {
    set((state) => ({ users: [...state.users, user] }));
  },
  
  updateUser: (id: string, user: Partial<User>) => {
    set((state) => ({
      users: state.users.map((u) => 
        u.id === id ? { ...u, ...user } : u
      ),
    }));
  },
  
  removeUser: (id: string) => {
    set((state) => ({
      users: state.users.filter((u) => u.id !== id),
    }));
  },
  
  refreshUsers: async (filters?: any) => {
    const { setLoading, setError } = get();
    setLoading('users', true);
    setError('users', null);
    
    try {
      const params = new URLSearchParams(filters || {});
      const response = await fetch(`/api/users?${params}`, {
        headers: getAuthHeaders(),
      });
      
      if (!response.ok) {
        throw new Error('获取用户列表失败');
      }
      
      const data = await response.json();
      get().setUsers(data.data || data);
    } catch (error) {
      setError('users', error instanceof Error ? error.message : '未知错误');
    } finally {
      setLoading('users', false);
    }
  },
  
  // 角色相关 - 简化实现，其他类似
  setRoles: (roles: Role[]) => {
    set((state) => ({
      roles,
      lastUpdated: { ...state.lastUpdated, roles: new Date().toISOString() },
    }));
  },
  
  addRole: (role: Role) => {
    set((state) => ({ roles: [...state.roles, role] }));
  },
  
  updateRole: (id: string, role: Partial<Role>) => {
    set((state) => ({
      roles: state.roles.map((r) => 
        r.id === id ? { ...r, ...role } : r
      ),
    }));
  },
  
  removeRole: (id: string) => {
    set((state) => ({
      roles: state.roles.filter((r) => r.id !== id),
    }));
  },
  
  refreshRoles: async (tenantId?: string) => {
    const { setLoading, setError } = get();
    setLoading('roles', true);
    setError('roles', null);
    
    try {
      const url = tenantId ? `/api/roles?tenantId=${tenantId}` : '/api/roles';
      const response = await fetch(url, {
        headers: getAuthHeaders(),
      });
      
      if (!response.ok) {
        throw new Error('获取角色列表失败');
      }
      
      const roles = await response.json();
      get().setRoles(roles);
    } catch (error) {
      setError('roles', error instanceof Error ? error.message : '未知错误');
    } finally {
      setLoading('roles', false);
    }
  },
  
  // 权限相关
  setPermissions: (permissions: Permission[]) => {
    set((state) => ({
      permissions,
      lastUpdated: { ...state.lastUpdated, permissions: new Date().toISOString() },
    }));
  },
  
  refreshPermissions: async () => {
    const { setLoading, setError } = get();
    setLoading('permissions', true);
    setError('permissions', null);
    
    try {
      const response = await fetch('/api/permissions', {
        headers: getAuthHeaders(),
      });
      
      if (!response.ok) {
        throw new Error('获取权限列表失败');
      }
      
      const permissions = await response.json();
      get().setPermissions(permissions);
    } catch (error) {
      setError('permissions', error instanceof Error ? error.message : '未知错误');
    } finally {
      setLoading('permissions', false);
    }
  },
  
  // 部门相关 - 简化实现
  setDepartments: (departments: Department[]) => {
    set((state) => ({
      departments,
      lastUpdated: { ...state.lastUpdated, departments: new Date().toISOString() },
    }));
  },
  
  addDepartment: (department: Department) => {
    set((state) => ({ departments: [...state.departments, department] }));
  },
  
  updateDepartment: (id: string, department: Partial<Department>) => {
    set((state) => ({
      departments: state.departments.map((d) => 
        d.id === id ? { ...d, ...department } : d
      ),
    }));
  },
  
  removeDepartment: (id: string) => {
    set((state) => ({
      departments: state.departments.filter((d) => d.id !== id),
    }));
  },
  
  refreshDepartments: async (organizationId?: string) => {
    const { setLoading, setError } = get();
    setLoading('departments', true);
    setError('departments', null);
    
    try {
      const url = organizationId ? `/api/departments?organizationId=${organizationId}` : '/api/departments';
      const response = await fetch(url, {
        headers: getAuthHeaders(),
      });
      
      if (!response.ok) {
        throw new Error('获取部门列表失败');
      }
      
      const departments = await response.json();
      get().setDepartments(departments);
    } catch (error) {
      setError('departments', error instanceof Error ? error.message : '未知错误');
    } finally {
      setLoading('departments', false);
    }
  },
  
  // 岗位相关 - 简化实现
  setPositions: (positions: Position[]) => {
    set((state) => ({
      positions,
      lastUpdated: { ...state.lastUpdated, positions: new Date().toISOString() },
    }));
  },
  
  addPosition: (position: Position) => {
    set((state) => ({ positions: [...state.positions, position] }));
  },
  
  updatePosition: (id: string, position: Partial<Position>) => {
    set((state) => ({
      positions: state.positions.map((p) => 
        p.id === id ? { ...p, ...position } : p
      ),
    }));
  },
  
  removePosition: (id: string) => {
    set((state) => ({
      positions: state.positions.filter((p) => p.id !== id),
    }));
  },
  
  refreshPositions: async (departmentId?: string) => {
    const { setLoading, setError } = get();
    setLoading('positions', true);
    setError('positions', null);
    
    try {
      const url = departmentId ? `/api/positions?departmentId=${departmentId}` : '/api/positions';
      const response = await fetch(url, {
        headers: getAuthHeaders(),
      });
      
      if (!response.ok) {
        throw new Error('获取岗位列表失败');
      }
      
      const positions = await response.json();
      get().setPositions(positions);
    } catch (error) {
      setError('positions', error instanceof Error ? error.message : '未知错误');
    } finally {
      setLoading('positions', false);
    }
  },
  
  // 订阅相关 - 简化实现
  setSubscriptionPlans: (subscriptionPlans: SubscriptionPlan[]) => {
    set((state) => ({
      subscriptionPlans,
      lastUpdated: { ...state.lastUpdated, subscriptionPlans: new Date().toISOString() },
    }));
  },
  
  setTenantSubscriptions: (tenantSubscriptions: TenantSubscription[]) => {
    set((state) => ({
      tenantSubscriptions,
      lastUpdated: { ...state.lastUpdated, tenantSubscriptions: new Date().toISOString() },
    }));
  },
  
  setOrganizationSubscriptions: (organizationSubscriptions: OrganizationSubscription[]) => {
    set((state) => ({
      organizationSubscriptions,
      lastUpdated: { ...state.lastUpdated, organizationSubscriptions: new Date().toISOString() },
    }));
  },
  
  refreshSubscriptionPlans: async () => {
    const { setLoading, setError } = get();
    setLoading('subscriptionPlans', true);
    setError('subscriptionPlans', null);
    
    try {
      const response = await fetch('/api/subscription-plans', {
        headers: getAuthHeaders(),
      });
      
      if (!response.ok) {
        throw new Error('获取订阅套餐失败');
      }
      
      const plans = await response.json();
      get().setSubscriptionPlans(plans);
    } catch (error) {
      setError('subscriptionPlans', error instanceof Error ? error.message : '未知错误');
    } finally {
      setLoading('subscriptionPlans', false);
    }
  },
  
  refreshTenantSubscriptions: async (tenantId?: string) => {
    const { setLoading, setError } = get();
    setLoading('tenantSubscriptions', true);
    setError('tenantSubscriptions', null);
    
    try {
      const url = tenantId ? `/api/tenant-subscriptions?tenantId=${tenantId}` : '/api/tenant-subscriptions';
      const response = await fetch(url, {
        headers: getAuthHeaders(),
      });
      
      if (!response.ok) {
        throw new Error('获取租户订阅失败');
      }
      
      const subscriptions = await response.json();
      get().setTenantSubscriptions(subscriptions);
    } catch (error) {
      setError('tenantSubscriptions', error instanceof Error ? error.message : '未知错误');
    } finally {
      setLoading('tenantSubscriptions', false);
    }
  },
  
  refreshOrganizationSubscriptions: async (organizationId?: string) => {
    const { setLoading, setError } = get();
    setLoading('organizationSubscriptions', true);
    setError('organizationSubscriptions', null);
    
    try {
      const url = organizationId ? `/api/organization-subscriptions?organizationId=${organizationId}` : '/api/organization-subscriptions';
      const response = await fetch(url, {
        headers: getAuthHeaders(),
      });
      
      if (!response.ok) {
        throw new Error('获取组织订阅失败');
      }
      
      const subscriptions = await response.json();
      get().setOrganizationSubscriptions(subscriptions);
    } catch (error) {
      setError('organizationSubscriptions', error instanceof Error ? error.message : '未知错误');
    } finally {
      setLoading('organizationSubscriptions', false);
    }
  },
  
  // 通用动作
  setLoading: (key: keyof DataState['loading'], loading: boolean) => {
    set((state) => ({
      loading: { ...state.loading, [key]: loading },
    }));
  },
  
  setError: (key: keyof DataState['errors'], error: string | null) => {
    set((state) => ({
      errors: { ...state.errors, [key]: error },
    }));
  },
  
  clearCache: () => {
    set(createDefaultState());
  },
  
  clearErrors: () => {
    set((state) => ({
      errors: Object.keys(state.errors).reduce((acc, key) => ({
        ...acc,
        [key]: null,
      }), {} as DataState['errors']),
    }));
  },
  
  // 查询辅助
  getTenantById: (id: string) => {
    return get().tenants.find((t) => t.id === id);
  },
  
  getOrganizationById: (id: string) => {
    return get().organizations.find((o) => o.id === id);
  },
  
  getUserById: (id: string) => {
    return get().users.find((u) => u.id === id);
  },
  
  getRoleById: (id: string) => {
    return get().roles.find((r) => r.id === id);
  },
  
  getPermissionById: (id: string) => {
    return get().permissions.find((p) => p.id === id);
  },
  
  getDepartmentById: (id: string) => {
    return get().departments.find((d) => d.id === id);
  },
  
  getPositionById: (id: string) => {
    return get().positions.find((p) => p.id === id);
  },
  
  // 关系查询
  getOrganizationsByTenant: (tenantId: string) => {
    return get().organizations.filter((o) => o.tenantId === tenantId);
  },
  
  getUsersByOrganization: (organizationId: string) => {
    return get().users.filter((u) => u.organizationId === organizationId);
  },
  
  getDepartmentsByOrganization: (organizationId: string) => {
    return get().departments.filter((d) => d.organizationId === organizationId);
  },
  
  getPositionsByDepartment: (departmentId: string) => {
    return get().positions.filter((p) => p.departmentId === departmentId);
  },
  
  getRolesByTenant: (tenantId: string) => {
    return get().roles.filter((r) => r.tenantId === tenantId);
  },
}));